package interfaz;

import clases.ClsContraladorEventos;
import clases.ClsDatabase;
import clases.ClsMetodos;
import clases.ClsValidacion;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTable;

/**
 *
 * @author mk
 */
public class dlg_Unidades extends javax.swing.JDialog {

    private ClsDatabase bd=new ClsDatabase();
    private ClsMetodos metodos=new ClsMetodos();
    private ClsContraladorEventos contraladorEventos=new ClsContraladorEventos();
    private JTable table;
    private dlgUnidades dialog;
    private String idUnidad="-1";
    private boolean editarUpdate=false;
    /**
     * Creates new form dlg_Unidades
     * @param parent
     * @param modal
     */
    public dlg_Unidades(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        this.setLocationRelativeTo(null);//Centramos la ventana
        initComponents();
    }

    public dlg_Unidades(java.awt.Frame parent, boolean modal,JDialog dialog,JTable table) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);//Centramos la ventana
        this.dialog=(dlgUnidades) dialog;
        this.table=table;
        metodos._iconJDialog(this);
        Limpiar();
    }
    // <editor-fold desc="UNIDADES CODE">
    //UNIDADES
    public void Editar(){
        int fila=table.getSelectedRow();//Obtenemos la fila seleccionada
        if (fila != -1) {//Si no se a seleccionado alguna row de la Tabla hacer...
           Object[][] datos=bd.select("unidad",
                    "idunidad,nombre,simbolo,estado",
                    "idunidad='"+table.getValueAt(fila, 0)+"' ");
            if (datos != null) {
                idUnidad=datos[0][0].toString();
                txaDescripcion.setText(datos[0][1].toString());
                txtSimboloU.setText(datos[0][2].toString());
//                if (datos[0][3].equals("A")) {
//                    tgbActivoU.setSelected(true);
//                    tgbInactivoU.setSelected(false);
//                }else{
//                    tgbActivoU.setSelected(false);
//                    tgbInactivoU.setSelected(true);
//                }
//                spnNivelU.setValue(new Integer(datos[0][4].toString()));
                txaDescripcion.setSelectionStart(0);
                txaDescripcion.setSelectionEnd(txaDescripcion.getText().length());
                editarUpdate=true;
                setVisible(true);
            } else {
                System.err.println("------------------------>ERROR NO PREVISTO<--------------------------------");
            }
        } else {
            javax.swing.JOptionPane.showMessageDialog(this, "Seleccione una Unidad a editar");
            dispose();
        }
    }

    public void Guardar(){
        String nombreString=txaDescripcion.getText().toString();
        boolean seRepite=true;
        if (editarUpdate) {//Si se presiona EDITAR, entonces el nombre se actualiza, no es un INSERT
            seRepite=false;
        }else{//Verificamos si se repite
            seRepite=bd.verif_repite("SELECT nombre FROM unidad WHERE nombre='"+nombreString+"'");
        }
        if (!seRepite) {//Verificamos si se Repite el Nombre de Unidad
            if (ClsValidacion.tieneCamposVacios(pnlAgregarUnidad)) {
                JOptionPane.showMessageDialog(null, "Se tiene que llenar todos los campos");
                return;
            }
            String simbolo=txtSimboloU.getText().toString();
//            int nivel=(int)spnNivelU.getValue();

            String estadoString="";
//            if (tgbActivoU.isSelected()) {
                estadoString="A";
//            }else{
//                estadoString="I";
//            }

            if (editarUpdate) {
                //UPDATE
                //Realizamos la consulta
                boolean seInserto=bd.update("unidad",
                        "nombre='"+nombreString+"',simbolo='"+simbolo
                        +"',estado='"+estadoString+"'",
                        "idunidad="+idUnidad);
                if (!seInserto) {
                    JOptionPane.showMessageDialog(null, "No se pudo Actualizar la Unidad");
                }
                editarUpdate=false;
            }else{
                //INSERT
                //Realizamos la consulta
                boolean seInserto=bd.insert("unidad",
                        "nombre,simbolo,nivel,estado",
                        "'"+nombreString+"','"+simbolo+"','2','"+estadoString+"'");
                if (!seInserto) {
                    JOptionPane.showMessageDialog(null, "No se pudo crear la Nueva Unidad");
                }
            }
            dialog._iniciar_U();
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(null, "Ya existe ese Nombre!!!");
            txaDescripcion.requestFocus();
            txaDescripcion.setSelectionStart(0);
            txaDescripcion.setSelectionEnd(txaDescripcion.getText().length());
        }
    }

    public void Cancelar(){
        this.dispose();
    }

    private void Limpiar(){
        txaDescripcion.setText("");
        txtSimboloU.setText("");
//        spnNivelU.setValue(0);
//        tgbActivoU.setSelected(true);
//        tgbInactivoU.setSelected(false);
        txaDescripcion.requestFocus();
    }
    // </editor-fold>

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlAgregarUnidad = new javax.swing.JPanel();
        btnGuardarU = new javax.swing.JButton();
        btnCancelarU = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtSimboloU = new javax.swing.JTextField();
        txaDescripcion = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Datos de Unidad");

        pnlAgregarUnidad.setBackground(new java.awt.Color(225, 235, 247));
        pnlAgregarUnidad.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btnGuardarU.setText("Aceptar");
        btnGuardarU.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarUActionPerformed(evt);
            }
        });
        pnlAgregarUnidad.add(btnGuardarU, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 150, 100, 31));

        btnCancelarU.setText("Cancelar");
        btnCancelarU.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarUActionPerformed(evt);
            }
        });
        pnlAgregarUnidad.add(btnCancelarU, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 150, 100, 31));

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, java.awt.Color.black));
        jPanel6.setOpaque(false);

        jLabel1.setText("Descripción:");

        jLabel2.setText("Abreviatura:");

        txtSimboloU.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtSimboloUKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txaDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtSimboloU, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(32, 32, 32))
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txaDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtSimboloU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(27, Short.MAX_VALUE))
        );

        pnlAgregarUnidad.add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 11, -1, -1));

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        pnlAgregarUnidad.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, 190));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlAgregarUnidad, javax.swing.GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlAgregarUnidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarUActionPerformed
        Guardar();
    }//GEN-LAST:event_btnGuardarUActionPerformed

    private void btnCancelarUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarUActionPerformed
        Cancelar();
    }//GEN-LAST:event_btnCancelarUActionPerformed

    private void txtSimboloUKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSimboloUKeyTyped
        contraladorEventos.cantidadMaximaCaracteresJTextField(evt, txtSimboloU, 5);
    }//GEN-LAST:event_txtSimboloUKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlg_Unidades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlg_Unidades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlg_Unidades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlg_Unidades.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlg_Unidades dialog = new dlg_Unidades(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelarU;
    private javax.swing.JButton btnGuardarU;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel pnlAgregarUnidad;
    private javax.swing.JTextField txaDescripcion;
    private javax.swing.JTextField txtSimboloU;
    // End of variables declaration//GEN-END:variables
}
